package com.unis.common.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import net.sf.json.JSONObject;


@Component
public class ElasticSearchHandler {
	private static TransportClient client = null;
	
	private static String indexName = "qwjsajxx";
	
	private static String indexType = "qwjsajxx";

	private static String clustername = "fdzpt-es";
//	private static String clustername = "fzj";
	private static String ipAddress = "68.89.99.93";
//	private static String ipAddress = "127.0.0.1";
	private static int port = 9300;
	
	private static Logger logger = LoggerFactory.getLogger(ElasticSearchHandler.class);
	/*private static Properties pro = null;
	
	static {
		try {
			String path = ResourceUtils.getURL("classpath:").getPath();
			logger.info(path);
			logger.info(path+"application.properties");
			pro = new Properties();
			InputStream in = new BufferedInputStream (new FileInputStream(path+"application.properties"));
			pro.load(in);
			indexName = pro.getProperty("indexName");
			indexType = pro.getProperty("indexType");
			clustername = pro.getProperty("clustername");
			ipAddress = pro.getProperty("ipAddress");
			port = Integer.parseInt(pro.getProperty("port"));

			logger.info(indexName +"==="+ clustername);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}*/
	
	/**
	 * 
	 * 功能描述:创建客户端连接ES服务
	 * @return
	 */
	public static TransportClient getClient() {
		try {
			/*String ipAddress = "127.0.0.1";*/
			/*int port = 9300;*/
			//程序中更改集群结点名称 并且设置client.transport.sniff为true来使客户端去嗅探整个集群的状态
			Settings settings = Settings.builder()
					.put("client.transport.sniff",false).put("cluster.name", clustername)
					.build();
			client = new PreBuiltTransportClient(settings);
			client.addTransportAddress(new TransportAddress(InetAddress.getByName(ipAddress), port));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		return  client;
	}
	
	
	/**
	 * 
	 * 功能描述:添加索引数据
	 * @param vo
	 * @return
	 */
	public synchronized static String createIndex(List<WholeAjxx> whole) {
		String doc_id = "";
		try {
			IndexRequestBuilder requestBuilder = getClient().prepareIndex(indexName,indexType);
			for(WholeAjxx vo : whole) {
				String jsonDate = JSONObject.fromObject(vo)+"";
				IndexResponse ir = requestBuilder.setId(vo.getAjid()).setSource(jsonDate,XContentType.JSON).execute().actionGet();
				logger.info("索引名:"+ir.getIndex());
			}
			//getClient().close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("哇哦，添加索引失败了");
		}
		return doc_id;
	}

	
	/**
	 * 功能描述:更新索引
	 */
	public static void updateIndex(List<WholeAjxx> voList) {
		try {
			UpdateRequest uRequest = new UpdateRequest();
			uRequest.index(indexName);
			uRequest.type(indexType);
			for(WholeAjxx vo : voList) {
				uRequest.id(vo.getAjid());
				uRequest.doc("{\"nr\":\""+vo.getNr()+"\"}", XContentType.JSON);
				getClient().update(uRequest).get();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("哇哦，更新索引失败了");
		}
	}

	
	
	
	/**
	 * 功能描述:查询
	 * @return
	 */
	public static List<WholeAjxx> searcher(Map<String,String> pmap,int from, int size) {
		List<WholeAjxx> list = new ArrayList<WholeAjxx>();
		BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
		String searchWord = pmap.get("nr");
		queryBuilder
		.should(QueryBuilders.wildcardQuery("nr", "*"+searchWord+"*"))
		//.should(QueryBuilders.fuzzyQuery(name, value));
		.should(QueryBuilders.queryStringQuery("nr:"+searchWord).defaultOperator(Operator.OR));
		queryBuilder.minimumShouldMatch(1);
		SearchResponse searchResponse = getClient().prepareSearch(indexName).setTypes(indexType)
	        .setQuery(queryBuilder).setFrom(from).setSize(size)
	        .setExplain(true)
	        .execute()
	        .actionGet();
		SearchHits hits = searchResponse.getHits();
		long totalHits = hits.getTotalHits();
		logger.info("查询到记录数=" + totalHits);
		SearchHit[] searchHists = hits.getHits();
		if(searchHists.length > 0) {
			for(SearchHit hit:searchHists){
				logger.debug("hit.getId() =" + hit.getId());
				String id = (String)hit.getSourceAsMap().get("ajid");
				String title =  (String) hit.getSourceAsMap().get("nr");
				String keyword = (String)hit.getSourceAsMap().get("ly");
                WholeAjxx vo = new WholeAjxx();
                vo.setAjid(id);
                vo.setNr(title);
                vo.setLy(keyword);
                list.add(vo);
			}
		}
		getClient().close();
		return list;
		
	}
	
	
	/**
	 * 功能描述:查询
	 * @return
	 */
	public static int searchercount(Map<String,String> pmap) {
		List<WholeAjxx> list = new ArrayList<WholeAjxx>();
		BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
		String searchWord = pmap.get("nr");
		queryBuilder
		.should(QueryBuilders.wildcardQuery("nr", "*"+searchWord+"*"))
		//.should(QueryBuilders.fuzzyQuery(name, value));
		.should(QueryBuilders.queryStringQuery("nr:"+searchWord).defaultOperator(Operator.OR));
		queryBuilder.minimumShouldMatch(1);
		SearchResponse searchResponse = getClient().prepareSearch(indexName).setTypes(indexType)
	        .setQuery(queryBuilder).setFrom(0).setSize(0)
	        .setExplain(true)
	        .execute()
	        .actionGet();
		SearchHits hits = searchResponse.getHits();
		long totalHits = hits.getTotalHits();
		
		getClient().close();
		return (int)totalHits;
		
	}


	public String getPath(){
		return this.getClass().getClassLoader().getResource("").getPath();
	}


	
	/**
	 * 功能描述:删除索引
	 * @param
	 */
	public static void DelIndex(String id) {
		try {
			QueryBuilder queryBuilder = QueryBuilders.termQuery("id", id);
			DeleteByQueryAction.INSTANCE.newRequestBuilder(getClient())
				.filter(queryBuilder)
				.source(indexName)
				.get();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("哇哦，删除索引失败了");
		}
		
	}
	
	
	
	
	
	public static void main(String[] args){

		/*ElasticSearchHandler el = new ElasticSearchHandler();
		System.out.println(el.getPath());*/

    	try{
    		//elasticsearch6.1.1版本测试
    		
    		//添加方法
    		/*KnowledgeVO vo = new KnowledgeVO();
    		vo.setId("1234567");
    		vo.setTitle("软件大集合");
    		vo.setKeyword("Java");
    		vo.setSource("Oracle");
    		vo.setContent("Java数据");
    		vo.setVersion("1.0");
    		vo.setCreatorName("某某某");
    		vo.setIndexId("AWizBU0ygy2IhqmdsetP");
    		vo.setCreateTime("2019-05-24 12:12:12");
    		String indexId = createIndex(vo);
    		System.out.println("文档id===="+indexId);*/
    		
    		/*WholeAjxx vo = new WholeAjxx();
    		 //更新方法(记得放入索引id)
    		 String id = "1234567";
    		 vo.setAjid(id);
    		 updateIndex(vo);*/
    		 
    		
    		//System.out.println(pro.getProperty("aa"));
    		//查询方法
    		/*while(1==1) {
    		String ss = "";
    		Scanner sc = new Scanner(System.in);
    		System.out.println("请输入条件:");
    		ss = sc.nextLine();
    		Map<String,String> param = new HashMap<String, String>();
    		param.put("searchWord", ss);
    		List<WholeAjxx> searcher = searcher(param,0,50);
    		for(int i=0;i<searcher.size();i++) {
    			String ajid = searcher.get(i).getAjid();
    			String nr = searcher.get(i).getNr();
    			String ly = searcher.get(i).getLy();
    			System.out.println("id:"+ajid+"\nly:"+ly);
    		}
    		}*/
    		//删除方法
    		//DelIndex("123456");
    		Map<String,String> param = new HashMap<String, String>();
    		param.put("nr", "简要案情");
    		List<WholeAjxx> list= searcher(param,0,100);
    		logger.info(list.size()+"");
    		
    		
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}
    }
}
